import 'dart:convert';
import 'package:flutter_app/domain/feed.dart';
import 'package:flutter_app/interface/base_presenter.dart';
import 'package:flutter_app/model/worm/worm_model.dart';
import 'package:flutter_app/utils/request.dart';
import 'package:flutter_app/page/worm/worm.dart';

/// Worm 页面主持人
class WormPresenter extends BasePresenter<WormPageState, WormModel> {
  WormPresenter() : super(WormModel());

  /// 静态变量，设置页数
  static int num = 1;

  /// 加载数据
  /// @param page 页码
  /// @param type 类型
  void loadData({int page = 1, String type = WormModel.REFRESH}) {
    if ('none' == view.netStatus) {
      view.onNotNetwork();
      return;
    }
    // 显示对话框
    view.onShowLoading();
    // 获取网络数据
    Request.instance.get(
        url: model.getWormApi(),
        // params: model.getWormParams(page, type),
        successCallback: (response) {
          view.onSuccess();
          Map<String, dynamic> json = jsonDecode(response.toString());
          Feed feed = Feed.fromJson(json);
          // print(feed.counts);
          if (page == 1) {
            view.onLoadFeed(feed);
          } else {
            view.onLoadMoreFeed(feed);
          }
        },
        errorCallback: (msg) {
          view.onFailed(msg);
          print(msg);
        });
  }

  /// 下拉刷新
  Future<void> onRefresh() async {
    // 延时去加载数据
    await Future.delayed(Duration(seconds: 3), () {
      // 加载数据
      this.loadData();
    });
  }

  // 加载更多
  Future<void> loadMoreData() async {
    await Future.delayed(Duration(seconds: 1), () {
      this.loadData(page: ++num, type: WormModel.LOADMORE);
    });
  }

  /// 获取图片地址
  /// @param userId 用户ID
  /// @param imgId 图片 ID
  String getImageUrl(int userId, int imgId) => model.getImageApi(userId, imgId);
}
